package com.cqupt.controller;


import com.cqupt.common.log.annotation.OperationLog;
import com.cqupt.pojo.*;
import com.cqupt.service.FileManagerService;
import com.cqupt.service.KnowledgeService;
import com.cqupt.service.SolrService;
import com.cqupt.utils.PageUtils;
import com.cqupt.utils.RegularMatcher;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@CrossOrigin
@Controller
@RequestMapping("konwledgeBase")
@ResponseBody
public class KnowledgeBaseController {

    @Autowired
    private KnowledgeService knowledgeService;
    @Autowired
    private FileManagerService fileManagerService;

    @Autowired
    private SolrService solrService;

    /**
     * 获取当前所有知识列表
     *
     * @param cur_page       当前页码
     * @param page_size      页面大小
     * @param type_id        知识类别
     * @param view_type      最新或最热（知识清单界面）
     * @param approvalStatus 审批状态
     * @param searchText     搜索关键字
     * @return
     */
    @RequestMapping("/getAllKonwledge")
    public ResponseMessage getAllKonwledge(@RequestParam(value = "currentPage") String cur_page,
                                           @RequestParam(value = "pageSize") String page_size,
                                           @RequestParam(value = "typeId", required = false, defaultValue = "-1") Integer type_id,
                                           @RequestParam(value = "viewType", required = false, defaultValue = "-1") Integer view_type,
                                           @RequestParam(value = "approvalStatus", required = false, defaultValue = "-1") Integer approvalStatus,
                                           @RequestParam(value = "searchText", required = false, defaultValue = "default") String searchText) {
        // 获取所有筛选后的知识列表
        List<Map<String, Object>> knowledgeList = knowledgeService.getAllKnowledge(type_id, view_type, approvalStatus, searchText);
        // 分页处理
        List<Map<String, Object>> PagedKnowledgeList = PageUtils.getDataListByCurPage(knowledgeList, cur_page, page_size);
        // 知识总数
        int totalNum = knowledgeList.size();
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("knowledgeList", PagedKnowledgeList);
        resultMap.put("totalNum", totalNum);

        if (knowledgeList.size() > 0) {
            responseMessage.setStatus(true);
            responseMessage.setContent(resultMap);
        } else {
            responseMessage.setStatus(false);
            responseMessage.setContent(resultMap);
        }
        return responseMessage;
    }


    /**
     * 创建新知识
     *
     * @param files   知识附件
     * @param request HttpServletRequest
     * @return
     */
    @OperationLog(level = "信息", object = "知识", operationType = "新增")
    @RequestMapping("/createKonwledge")
    public ResponseMessage createKonwledge(@RequestParam(value = "file") MultipartFile[] files, HttpServletRequest request) {

        // 知识名称
        String knowledgeName = request.getParameter("knowledgeName");
        // 标签名字
        String labelName = request.getParameter("labelName");
        // 知识类别（带父级）
        String type = request.getParameter("type");
        // 知识类别（最后一级）
        String[] type_arr = type.split(",");
        String simType = type_arr[type_arr.length - 1];
        // 问题描述键值表达式
        String alertKey = request.getParameter("alertKey");
        // 问题名称
        String problemName = request.getParameter("problemName");
        // 解决方案
        String resolution = request.getParameter("description");
        // 审批状态（新增知识默认未审批）
        String approval = request.getParameter("approval");
        // 提交者
        String submit_user = request.getParameter("submit_user");
        // 提交时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(new Date());
        // 浏览次数（初始为0次）
        int view_count = 0;
        // 预处理知识的键值，提取初公共键值
        String CommonKey = RegularMatcher.RE_Matcher(alertKey);
        // 初始化知识类
        Knowledge knowledge = new Knowledge(knowledgeName, labelName, type, simType, problemName, alertKey, resolution, approval, CommonKey, submit_user, date, view_count);
        // 获取返回的主键（知识id）
        int primary_key = (int) knowledgeService.insertKnowledge(knowledge);
        // 同步跟新索引库
        SearchInfo searchInfo = new SearchInfo(String.valueOf(primary_key), knowledgeName, labelName, type, problemName, alertKey, resolution, approval, CommonKey, submit_user, date, null);
        try {
            solrService.addAndUpdateIndex(searchInfo);
        } catch (IOException | SolrServerException e) {
            e.printStackTrace();
        }
        // 知识上传到服务端
        boolean flag = fileManagerService.uploadFiles(files, primary_key, submit_user, date);

        Map<String, Object> resMap = new HashMap<>();
        ResponseMessage responseMessage = new ResponseMessage();
        resMap.put("log_objectName", knowledgeName);
        if (flag == true) {
            resMap.put("log_description", "新增知识[" + knowledgeName + "]");
            responseMessage.setStatus(true);
        } else {
            responseMessage.setStatus(false);
        }
        responseMessage.setContent(resMap);
        return responseMessage;
    }

    /**
     * 删除知识操作
     *
     * @param body 获取前端的body对象
     * @return
     */
    @OperationLog(level = "信息", object = "知识", operationType = "删除知识")
    @RequestMapping("/deleteKonwledge")
    public ResponseMessage deleteKonwledgeByID(@RequestBody Map<String, Object> body) {
        // 获取要删除的知识id
        Integer id = (int) body.get("knowledgeID");
        // 获取要删除的知识名称
        String knowledgeName = (String) body.get("knowledgeName");
        // 根据知识id进行删除知识
        int flag = knowledgeService.deleteKnowledge(id);
        // 在solr中同步删除
        try {
            // solr中id为字符串
            solrService.deleteIndexById(id + "");
        } catch (IOException | SolrServerException e) {
            e.printStackTrace();
        }
        // 删除对应知识所关联的附件
        boolean flagDel = fileManagerService.deleteFiles(id);
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("flag", flag);
        resultMap.put("log_objectName", knowledgeName);
        if (flag > 0 && flagDel == true) {
            responseMessage.setStatus(true);
            resultMap.put("log_description", "");
        } else {
            responseMessage.setStatus(false);
            responseMessage.setErrorCode("");
            responseMessage.setContent(resultMap);
        }
        responseMessage.setContent(resultMap);
        return responseMessage;
    }


    /**
     * 更新知识
     *
     * @param files      更新的附件列表
     * @param closureIds 附件id
     * @param request
     * @return
     */
    @OperationLog(level = "信息", object = "知识", operationType = "修改知识")
    @RequestMapping("/updateKonwledge")
    public ResponseMessage updateUser(@RequestParam(value = "file") MultipartFile[] files,
                                      @RequestParam(value = "closureIds", required = false, defaultValue = "0") String[] closureIds,
                                      HttpServletRequest request) {
        // 获取更新后的知识的id
        int id = Integer.parseInt(request.getParameter("id"));
        // 获取更新后的知识名称
        String knowledgeName = request.getParameter("knowledgeName");
        // 获取更新后的标签名称
        String labelName = request.getParameter("labelName");
        // 获取更新后的知识类别（带父级）
        String type = request.getParameter("type");
        // 获取更新后的知识类别（不带父级）
        String[] type_arr = type.split(",");
        String simType = type_arr[type_arr.length - 1];
        // 获取更新后的知识问题键值表达式
        String alertKey = request.getParameter("alertKey");
        // 获取更新后的问题名称
        String problemName = request.getParameter("problemName");
        // 获取更新后的解决方案
        String resolution = request.getParameter("description");
        // 获取更新后的审批状态
        String approval = request.getParameter("approval");
        // 获取更新后的知识的id
        String submit_user = request.getParameter("submit_user");
        // 获取更新前的知识类别（为审计日志功能所用）
        String init_type = request.getParameter("init_type");
        // 获取当前更新时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(new Date());
        // 知识浏览次数
        //int view_count = Integer.parseInt(request.getParameter("view_count"));
        // 获取修改后的类别
        String alter_type = type.split(",")[type.split(",").length - 1];
        // 将知识类别id转换为中文名称
        String init_type_CN = knowledgeService.getTypeNameByID(Integer.parseInt(init_type));
        String alter_type_CN = knowledgeService.getTypeNameByID(Integer.parseInt(alter_type));

        // 预处理公共键值
        String commonKey = RegularMatcher.RE_Matcher(alertKey);
        Knowledge knowledge = new Knowledge(id, knowledgeName, labelName, type, simType, problemName, alertKey, resolution, approval, commonKey, submit_user, date);
        // 更新知识
        int count = knowledgeService.updateKnowledge(knowledge);
        // 同步跟新索引库
        SearchInfo searchInfo = new SearchInfo(String.valueOf(id), knowledgeName, labelName, type, problemName, alertKey, resolution, approval, commonKey, submit_user, date, null);
        try {
            solrService.addAndUpdateIndex(searchInfo);
        } catch (IOException | SolrServerException e) {
            e.printStackTrace();
        }
        boolean flag = fileManagerService.updateFiles(files, id, closureIds, submit_user, date);
        for (int i = 0; i < closureIds.length; i++) {
            System.out.println("closureIds" + closureIds[i]);
        }

        Map<String, Object> resMap = new HashMap<>();
        ResponseMessage responseMessage = new ResponseMessage();
        resMap.put("log_objectName", knowledgeName + "(id:" + id + ")");
        if (flag == true) {
            resMap.put("log_description", "修改类别[" + init_type_CN + "]->[" + alter_type_CN + "]");
            responseMessage.setStatus(true);
        } else {
            responseMessage.setErrorCode("");
            responseMessage.setStatus(false);
        }
        responseMessage.setContent(resMap);
        return responseMessage;
    }

    /**
     * 根据知识id查询知识
     *
     * @param body
     * @return
     */
    @RequestMapping("/getKonwledgeById")
    public ResponseMessage getKonwledgeByID(@RequestBody Map<String, Object> body) {
        // 获取知识id
        int id = (int) body.get("knowledgeID");
        // 根据知识id获取知识map
        Map<String, Object> konwledgeAndClosure = knowledgeService.getKnowledgeById(id);

        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("konwledgeAndClosure", konwledgeAndClosure);
        if (konwledgeAndClosure != null) {
            responseMessage.setStatus(true);
            responseMessage.setContent(resultMap);
        } else {
            responseMessage.setStatus(false);
            responseMessage.setContent(resultMap);
        }
        return responseMessage;
    }

    /**
     * 知识审批
     *
     * @param body
     * @return
     */
    @RequestMapping("/knowledgeApproval")
    public ResponseMessage konwledgeApproval(@RequestBody Map<String, Object> body) {

        int id = (int) body.get("id");
        int approval = (int) body.get("approval");
        String approval_man = (String) body.get("approval_man");
        String knowledgeName = (String) body.get("knowledgeName");
        boolean flag = knowledgeService.approvalKnowledge(id, approval, approval_man);
        Map<String, Object> resMap = new HashMap<>();
        ResponseMessage responseMessage = new ResponseMessage();
        resMap.put("log_objectName", knowledgeName);
        if (flag == true) {
            if (approval == 1) {
                resMap.put("log_description", "审批通过！");
            } else {
                resMap.put("log_description", "审批失败！");
            }
            responseMessage.setStatus(true);
        } else {
            responseMessage.setStatus(false);

            responseMessage.setErrorCode("");
        }
        responseMessage.setContent(resMap);
        return responseMessage;
    }

    @OperationLog(level = "信息", object = "知识", operationType = "审批")
    @RequestMapping("/knowledgeApprovalSuccess")
    public ResponseMessage knowledgeApprovalSuccess(@RequestBody Map<String, Object> body) {

        int id = (int) body.get("id");
        int approval = (int) body.get("approval");
        String approval_man = (String) body.get("approval_man");
        String knowledgeName = (String) body.get("knowledgeName");
        boolean flag = true;
        Map<String, Object> resMap = new HashMap<>();
        ResponseMessage responseMessage = new ResponseMessage();
        resMap.put("log_objectName", knowledgeName);
        if (flag == true) {
            resMap.put("log_description", "审批通过！");
            responseMessage.setStatus(true);
        } else {
            responseMessage.setStatus(false);
            responseMessage.setErrorCode("");
        }
        responseMessage.setContent(resMap);
        return responseMessage;
    }

    @OperationLog(level = "警告", object = "知识", operationType = "审批")
    @RequestMapping("/knowledgeApprovalFail")
    public ResponseMessage knowledgeApprovalFail(@RequestBody Map<String, Object> body) {

        int id = (int) body.get("id");
        int approval = (int) body.get("approval");
        String approval_man = (String) body.get("approval_man");
        String knowledgeName = (String) body.get("knowledgeName");
        boolean flag = true;
        Map<String, Object> resMap = new HashMap<>();
        ResponseMessage responseMessage = new ResponseMessage();
        resMap.put("log_objectName", knowledgeName);
        if (flag == true) {
            resMap.put("log_description", "审批失败！");
            responseMessage.setStatus(true);
        } else {
            responseMessage.setStatus(false);

            responseMessage.setErrorCode("");
        }
        responseMessage.setContent(resMap);
        return responseMessage;
    }

    /**
     * 知识采纳
     *
     * @param body
     * @return
     */
    @RequestMapping("/adoptKnowledge")
    public ResponseMessage adoptKnowledge(@RequestBody Map<String, Object> body) {
        // 获取知识id
        int knowledgeid = (int) body.get("knowledgeid");
        // 知识的关联公共键值
        String commonkey = (String) body.get("commonkey");
        // 采纳知识，知识与公共键值关联
        int flag = knowledgeService.adoptKnowledge(knowledgeid, commonkey);
        ResponseMessage responseMessage = new ResponseMessage();
        if (flag != -1) {
            responseMessage.setStatus(true);
            responseMessage.setContent(null);
        } else {
            responseMessage.setStatus(false);
            responseMessage.setContent(null);
        }
        return responseMessage;
    }

    /**
     * 根据知识id增加浏览次数
     *
     * @param knowledgeId 知识id
     * @return
     */
    @RequestMapping("/setKnowledgeViewCount")
    public ResponseMessage addViewCount(@RequestParam(value = "id") int knowledgeId) {
        // 将知识浏览次数+1
        int flag = knowledgeService.setKnowledgeViewCount(knowledgeId);
        ResponseMessage responseMessage = new ResponseMessage();
        if (flag != -1) {
            responseMessage.setStatus(true);
            responseMessage.setContent(null);
        } else {
            responseMessage.setStatus(false);
            responseMessage.setContent(null);
        }
        return responseMessage;
    }

    /**
     * 按条件获取所有的分类
     *
     * @param body params={type=3, pagenum=1, pagesize=5}
     * @return
     */
    @RequestMapping(value = "/get_all_type")
    public ResponseMessage getAllType(@RequestBody Map<String, Object> body) {
        Map<String, Object> map = (Map<String, Object>) body.get("params");
        ResponseMessage result = new ResponseMessage();
        // 获取所有的类型
        List<Type> types = knowledgeService.getAllType(map);
        // 获取类型的综述
        Integer total = knowledgeService.getAllTypeCount();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", types);
        resultMap.put("total", total);
        result.setContent(resultMap);
        result.setStatus(types.size() != 0);
        return result;
    }

    /**
     * 添加分类
     *
     * @param body {typeName=撒打算啊实打实, typePId=4, typeLevel=2}
     * @return 是否添加成功
     */
    @OperationLog(level = "信息", object = "知识分类", operationType = "新增")
    @RequestMapping("/add_type")
    public ResponseMessage addType(@RequestBody Map<String, Object> body) {
        ResponseMessage message = new ResponseMessage();
        Map<String, Object> resMap = new HashMap<>();
        String typeName = (String) body.get("typeName");
        int typePId = (int) body.get("typePId");
        int typeLevel = (int) body.get("typeLevel");
        Type t = new Type(typeName, typePId, typeLevel);
        Integer i = knowledgeService.addType(t);
        // 以下为将添加分类操作记录到日志中
        resMap.put("log_objectName", typeName);
        if (i == 1) {
            message.setStatus(true);
            resMap.put("log_description", "新增知识分类[" + typeName + "]");
        }
        message.setContent(resMap);
        return message;
    }

    /**
     * 通过类型的 id 删除指定类型
     *
     * @param body 包含类型的 id
     * @return
     */
    @OperationLog(level = "警告", object = "知识分类", operationType = "删除")
    @RequestMapping("/delete_type_by_id")
    public ResponseMessage deleteTypeById(@RequestBody Map<String, Object> body) {
        ResponseMessage message = new ResponseMessage();
        Map<String, Object> resMap = new HashMap<>();
        List<Integer> ids = (List<Integer>) body.get("params");
        String name = knowledgeService.getTypeNameByID(ids.get(0));
        Integer i = knowledgeService.deleteTypeById(ids);
        // 以下为日志相关的操作
        resMap.put("log_objectName", name);
        if (i >= 1) {
            message.setStatus(true);
            resMap.put("log_objectName", name);
            resMap.put("log_description", "删除分类[" + name + "]");
        } else {
            message.setErrorCode("当前分类[" + name + "]" + "下有知识，不能移除");
            message.setStatus(false);
        }
        message.setContent(resMap);
        return message;
    }

    /**
     * 根据分类的id，更新分类的名称
     *
     * @param body 包含分类id的集合
     * @return
     */
    @RequestMapping("/update_type_by_id")
    public ResponseMessage updateType(@RequestBody Map<String, Object> body) {
        ResponseMessage message = new ResponseMessage();
        Map<String, Object> map = (Map<String, Object>) body.get("params");
        Type t = new Type((int) map.get("typeId"), (String) map.get("typeName"));
        Integer i = knowledgeService.updateType(t);
        message.setStatus(i == 1);
        return message;
    }

    /**
     * 根据知识的id获取附件信息
     *
     * @param params
     * @return
     */
    @RequestMapping("/get_closure_by_knowledgeId")
    public ResponseMessage getClosureByKnowledgeId(@RequestBody Map<String, Object> params) {
        System.out.println(params);
        ResponseMessage message = new ResponseMessage();
        List<Enclosure> closure = knowledgeService.getClosureByKnowledgeId(params);
        Map<String, Object> res = new HashMap<>();
        res.put("result", closure);
        message.setStatus(closure.size() != 0);
        message.setContent(res);
        return message;
    }
}
